﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using System.Data.Objects;
using System.Data;

namespace Core.Models
{
    public class DatabaseEntities : BlogMvcEntities
    {
        public DatabaseEntities() : base()
        {
            SavingChanges += DatabaseSavingChange;
        }

        private void DatabaseSavingChange(object sender, EventArgs e)
        {
            var context = sender as ObjectContext;
            if (context != null)
            {
                foreach (ObjectStateEntry entry in context.ObjectStateManager.GetObjectStateEntries(EntityState.Added | EntityState.Modified))
                {
                    if (entry.Entity is IBaseObject)
                    {
                        var obj = (IBaseObject)entry.Entity;
                        if (entry.State == EntityState.Added)
                        {
                            obj.CreatedDate = DateTime.Now;
                            obj.ModifyDate = DateTime.Now;
                        }
                        if (entry.State == EntityState.Modified)
                        {
                            obj.ModifyDate = DateTime.Now;
                        }
                    }
                }
            }//---End if(context!=null)
        }
    }
}
